#include "crc_tools.h"

uint16_t crc16_modbus(uint8_t *data, uint16_t length) {
  uint16_t crc = 0xFFFF;
  for (uint16_t i = 0; i < length; i++) {
    crc ^= data[i];
    for (uint8_t j = 0; j < 8; j++) {
      if (crc & 0x0001) {
        crc = (crc >> 1) ^ 0xA001;
      } else {
        crc >>= 1;
      }
    }
  }
  return crc;
}

uint32_t crc32(uint8_t *data, uint16_t len) {  
  uint32_t crc = 0xFFFFFFFF;  
  for (uint16_t i = 0; i < len; i++) {  
      crc ^= data[i];  
      for (uint8_t j = 0; j < 8; j++) {  
          if (crc & 0x00000001) {  
              crc = (crc >> 1) ^ 0xEDB88320;  
          } else {  
              crc >>= 1;  
          }  
      }  
  }  
  return crc ^ 0xFFFFFFFF;  
}

uint8_t crc8_ccitt(const uint8_t *data, uint16_t length) {
    uint8_t crc = 0x00;
    for (uint16_t i = 0; i < length; i++) {
        crc ^= data[i];
        for (uint8_t j = 0; j < 8; j++) {
            if (crc & 0x80) {
                crc = (crc << 1) ^ 0x07;
            } else {
                crc <<= 1;
            }
        }
    }
    return crc;
}
